'''
Description: 设备挂起模块
Author: liutq
Date: 2021-04-03 11:06:46
LastEditTime: 2021-04-11 00:22:23
LastEditors: liutq
Reference: 
'''
import socket
from Config import conf

class DeviceHolder:
    '''
    @description: 设备挂起器类
    @param  {*}
    @return {*}
    @param {*} self
    @param {*} parent：父对象
    @param {*} ip：本机IP
    '''
    def __init__(self,parent,ip):
        # 父对象
        self.parent = parent
        # 建立UDP socket
        self.socketUDP = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
        # 绑定设备扫描端口
        self.socketUDP.bind((ip,conf.device_scan_port))

    '''
    @description: 设备挂起函数
    @param  {*}
    @return {*}
    @param {*} self
    '''
    def hold(self):
        # 不断接收消息
        while True:
            # 接收UDP消息
            data,addr = self.socketUDP.recvfrom(1024)
            # 如果是广播消息，返回本机用户名，头像和地址信息
            if data == b'broadcast':
                self.socketUDP.sendto(('here:%s:%d'%(conf.username,conf.myavatar)).encode("utf-8"),addr)
